package com.github.bridge.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

public class JacksonUtil {


    // 创建一个 ObjectMapper 实例，由于 ObjectMapper 是线程安全的，我们可以将其定义为静态变量
    private static final ObjectMapper objectMapperNonEmpty = new ObjectMapper()
            .setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    private static final ObjectMapper objectMapper = new ObjectMapper()
            .setSerializationInclusion(JsonInclude.Include.NON_NULL);

    /**
     * 将 JSON 字符串转换为指定的 Java 对象
     *
     * @param jsonStr JSON 字符串
     * @param clazz   目标 Java 类的 Class 对象
     * @param <T>     目标 Java 类的类型
     * @return 转换后的 Java 对象
     * @throws Exception 转换过程中发生的异常
     */
    @SneakyThrows
    public static <T> T toBean(String jsonStr, Class<T> clazz) {
        return objectMapperNonEmpty.readValue(jsonStr, clazz);
    }


    @SneakyThrows
    public static String toJsonStr(Object obj) {
        return objectMapperNonEmpty.writeValueAsString(obj);
    }

    @SneakyThrows
    public static String toJsonStrAll(Object obj) {
        return objectMapper.writeValueAsString(obj);
    }
}
